package com.go8.trade.service;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.go8.trade.mapper.OrderDetailMapper;
import com.go8.trade.mapper.OrderMapper;
import com.go8.trade.mapper.OrderPayMapper;
import com.go8.trade.mapper.OrderShipMapper;
import com.go8.trade.pojo.Order;
import com.go8.trade.pojo.OrderDetail;
import com.go8.trade.pojo.OrderPay;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private OrderShipMapper orderShipMapper;
	@Autowired
	private OrderPayMapper orderPayMapper;
	
	@Override
	public void add(Order order) {
		Date now = new Date();
		order.setGmtCreate(now);
		order.setGmtModified(now);
		order.setStatus((byte)1);
		orderMapper.insert(order);
		
		List<OrderDetail> details = order.getDetails();
		for(int i=0;i<details.size();i++) {
			details.get(i).setOrderId(order.getId());
			orderDetailMapper.insert(details.get(i));
		}
		
		order.getShip().setOrderId(order.getId());
		order.getShip().setGmtCreate(now);
		order.getShip().setGmtModified(now);
		orderShipMapper.insert(order.getShip());
	}
	
	//记录支付信息，如果成功付款，修改订单状态
	@Override
	public void updateOrderStatus(OrderPay orderPay) {
		Date now = new Date();
		orderPay.setGmtCreate(now);
		orderPay.setGmtModified(now);
		orderPayMapper.insertSelective(orderPay);
		
		if(orderPay.getPayStatus().equals("TRADE_SUCCESS")) {
			Order record = new Order();
			record.setId(orderPay.getOrderId());
			record.setStatus((byte)2);
			orderMapper.updateByPrimaryKeySelective(record);
		}
	}

	@Override
	public Order get(long id) {
		return orderMapper.selectOrderAndShipById(id);
	}

	@Override
	public List<OrderDetail> getDetailsByOrderId(long orderId) {
		return orderDetailMapper.selectDetailsByOrderId(orderId);
	}

}
